<template>
  <div class="search-bar">
    <form action="/">
      <van-search
        v-model="inputKeyword"
        show-action
        :placeholder="placeholder"
        @update:model-value="handleInput"
        @search="handleSearch"
        @clear="triggerSearch('')"
        @cancel="handleCancel"
      />
    </form>
  </div>
      
  <template v-if="isInit">
    <search-hot
      :hotwords="hots"
      @select="triggerSearch"
    />
    <search-history 
      :historys="historys" 
      @select="triggerSearch"
      @clear="handleHistoryClear(historys)"
    ></search-history>
  </template>

  <transition name="fade">
    <search-suggest v-if="isInput" :suggests="suggests" @select="triggerSearch"></search-suggest>
  </transition>

  <transition name="fade">
    <search-result v-if="isResult"></search-result>
  </transition>

</template>

<script>
import { Search as VanSearch } from 'vant'
import SearchHot from './hot'
import SearchHistory from './history'
import SearchSuggest from './suggest'
import SearchResult from './result'
import useSearch from './hooks/useSearch'
import useHot from './hooks/useHot'
import useHistory from './hooks/useHistory'
export default {
  name: 'Search',
  components: {
    VanSearch,
    SearchHot,
    SearchHistory,
    SearchSuggest,
    SearchResult
  },
  props: {
    keyword: {
      type: String
    }
  },
  setup(props) {
    const { isInit, isInput, isResult, inputKeyword, placeholder, historys, suggests, handleInput, triggerSearch, handleCancel, handleSearch } = useSearch(props)
    const { handleHistoryClear } = useHistory()
    const { hots } = useHot()
    return {
      inputKeyword,
      placeholder,
      isInit,
      isInput,
      isResult,
      historys,
      suggests,
      hots,
      handleInput,
      triggerSearch,
      handleCancel,
      handleSearch,
      handleHistoryClear
    }
  }
}
</script>

<style lang="scss" scoped>
  .search-bar {
    position: sticky;
    top: 0;
    z-index: 2;
    background-color: $color-white;
    backface-visibility: hidden;
    .van-search__action{
      color: $theme-color;
    }    
  }
  .fade-enter-active,
  .fade-leave-active {
    transition: opacity 0.5s ease;
  }

  .fade-enter-from,
  .fade-leave-to {
    opacity: 0;
  }
</style>